<template>
  <!-- 路径导航 -->
  <div class="navigation-header">
    <Breadcrumb
        :pathStack="pathStack"
        @go-root="handleGoRoot"
        @navigate="handleNavigate"
    />
  </div>

  <!-- 操作工具栏 -->
  <div class="operation-bar-container">
    <OperationBar
        :isDisabled="pathStack.length === 0"
        :isRecycle="true"
        @go-back="handleGoBack"
        @upload="handleUpload"
    />
  </div>

  <!-- 文件列表 -->
  <el-row :gutter="20" class="file-grid">
    <el-col
        v-for="file in filteredFiles"
        :key="file.fileId"
        :xs="12" :sm="8" :md="6" :lg="4"
        class="file-grid-item"
    >
      <!-- 新增 @click 事件绑定 -->
      <div class="file-card" @dblclick="handleFileOpen(file)">
        <div class="file-card-header">
          <FileTypeIcon :file="file"/>
        </div>
        <div class="file-card-body">
          <div class="file-name">{{ file.fileName }}</div>
        </div>
        <div class="file-actions">
          <el-tooltip content="恢复文件" placement="top">
            <el-button
                size="small"
                type="success"
                plain
                @click="handleRestore(file)"
            >
              <el-icon>
                <DocumentAdd/>
              </el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="彻底删除" placement="top">
            <el-button
                size="small"
                type="danger"
                plain
                @click="handleDeleteForever(file)"
            >
              <el-icon>
                <DocumentDelete/>
              </el-icon>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </el-col>
  </el-row>

  <!-- 分页组件 -->
  <div class="pagination-container">
    <CustomPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        @page-change="loadFiles"
    />
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteDocumentApi, loadFilesApi, updateDocumentApi} from "@/utils/API/file-core/Index.js";

import {hideLoading, showLoading} from "@/utils/LoadingUtil";

const pathStack = ref([]);
const currentDirectoryId = ref(null);  // 新增
// 状态管理
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchQuery = ref("");
const fileList = ref([]);

// 计算过滤后的文件列表
const filteredFiles = computed(() => {
  return fileList.value.filter(file =>
      file.fileName.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

// 面包屑封装成字符串
const filteredBreadcrumb = () => {
  // 根目录返回空字符串（根据后端需求可能需要调整为 '/'，可根据实际接口要求修改）
  if (pathStack.value.length === 0) return '/';
  // 非根目录提取每个目录的fileName并用斜杠连接（原pathStack存储对象数组）
  const pathNames = pathStack.value.map(dir => dir.fileId);
  return '/' + pathNames.join('/') + '/';
}

// 加载回收站文件（修正API参数，新增parentId支持目录导航）
const loadFiles = async () => {
  try {
    showLoading()
    const response = await loadFilesApi({
      filePath: filteredBreadcrumb(),
      current: currentPage.value,
      size: pageSize.value,
      status: 0
    });

    if (response.code === 200) {
      fileList.value = response.data.records;
      total.value = response.data.records.length
    }
  } catch (error) {
    ElMessage.error("文件加载失败：" + error.message);
  } finally {
    hideLoading();
  }
};

// 文件打开逻辑（核心实现）
const handleFileOpen = (file) => {
  if (file.fileType === "folder") {
    // 存储包含 fileName 和 fileId 的对象到路径栈
    pathStack.value.push({fileName: file.fileName, fileId: file.fileId});
    currentDirectoryId.value = file.fileId;
    currentPage.value = 1;
    loadFiles();
  } else {
    console.log('打开底层文件:', file.fileName);
  }
};

// 恢复文件
const handleRestore = async (file) => {
  try {
    await ElMessageBox.confirm(
        `确定要恢复文件「${file.fileName}」吗？`,
        "恢复确认",
        {type: "warning"}
    );

    const response = await updateDocumentApi({
      fileId: file.fileId,
      status: 1  // 切换删除状态
    })

    if (response.code === 200) {
      ElMessage.success("文件恢复成功");
      await loadFiles(); // 刷新列表
    } else {
      ElMessage.error(response.msg || "恢复失败");
    }
  } catch (error) {
    if (error !== "cancel") ElMessage.error("恢复操作取消");
  }
};

// 彻底删除文件
const handleDeleteForever = async (file) => {
  try {
    await ElMessageBox.confirm(
        `确定要彻底删除文件「${file.fileName}」吗？删除后无法恢复！`,
        "危险操作",
        {type: "error"}
    );
    const response = await deleteDocumentApi(file.fileId);
    if (response.code === 200) {
      ElMessage.success("文件彻底删除成功");
      await loadFiles(); // 刷新列表
    } else {
      ElMessage.error(response.msg || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") ElMessage.error("删除操作取消");
  }
};

// 初始化加载
onMounted(() => {
  loadFiles()
})

// 面包屑事件处理
const handleGoRoot = () => {
  // 回到根目录逻辑（根据业务需求实现）
  pathStack.value = [];
  loadFiles();
};

// 面包屑目录导航
const handleNavigate = (dir) => {
  // 导航到指定目录逻辑（根据业务需求实现）
  pathStack.value = pathStack.value.slice(0, pathStack.value.indexOf(dir) + 1);
  loadFiles();
};

// 操作栏事件处理
const handleGoBack = () => {
  // 返回上级目录逻辑（根据业务需求实现）
  if (pathStack.value.length > 0) {
    pathStack.value.pop();
    loadFiles();
  }
};

const handleUpload = () => {
  // 上传文件逻辑（回收站可能不需要，可根据业务需求调整）
  ElMessage.warning("回收站中暂不支持上传文件");
};
</script>

<style scoped>
.navigation-header {
  padding: 0 16px;
  margin-bottom: 12px;
}

.operation-bar-container {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.file-grid {
  padding: 0 10px;
}

.file-grid-item {
  margin-bottom: 16px;
}

.file-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
  cursor: pointer;
}

.file-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.file-card-header {
  margin-bottom: 12px;
  display: flex;
  justify-content: center;
}

.file-card-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.file-name {
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
}

.file-actions {
  margin-top: 16px;
  padding-top: 12px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.file-actions .el-button {
  padding: 6px;
  width: 40px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-container {
  margin-top: 24px;
  padding: 0 8px;
  display: flex;
  justify-content: center;
}
</style>